<!-- 供货商售后反馈页面 -->
<template>
  <div>
    <base-table ref="table" :search-params="searchParams" :columns="columnsAction" :async-fc="page">
      <template #tableHeader>
        <t-button @click="refresh">刷新</t-button>
      </template>
    </base-table>

    <!-- 售后详情弹窗 -->
    <t-dialog v-model:visible="modalOpen" width="45%" @confirm="onModalSubmit">
      <div class="feedback-detail">
        <div class="detail-content">
          <div class="detail-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ submitForm.orderId }}</span>
          </div>
          <div class="detail-item">
            <span class="label">售后类型：</span>
            <span class="value">{{ getTypeText(submitForm.type) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">申请原因：</span>
            <span class="value">{{ submitForm.reason }}</span>
          </div>
          <div class="detail-item">
            <span class="label">问题描述：</span>
            <span class="value">{{ submitForm.description }}</span>
          </div>
          <div v-if="submitForm.images" class="detail-item">
            <span class="label">相关图片：</span>
            <div class="value image-list">
              <img
                v-for="(img, index) in submitForm.images"
                :key="index"
                :src="img"
                class="feedback-image"
                @click="handlePreviewImage(img)"
              />
            </div>
          </div>
          <div class="detail-item">
            <span class="label">申请状态：</span>
            <span class="value">
              <t-tag :theme="getStatusTheme(submitForm.status)">{{ getStatusText(submitForm.status) }}</t-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatTime(submitForm.createTime) }}</span>
          </div>
          <div v-if="submitForm.handleNote" class="detail-item">
            <span class="label">处理备注：</span>
            <span class="value">{{ submitForm.handleNote }}</span>
          </div>

          <!-- 处理表单 -->
          <template v-if="submitForm.status === 0">
            <div class="handle-form">
              <t-divider>处理表单</t-divider>
              <t-form ref="form" :data="handleForm" :rules="rules">
                <t-form-item label="处理结果" name="status">
                  <t-radio-group v-model="handleForm.status">
                    <t-radio-button :value="1">接受处理</t-radio-button>
                    <t-radio-button :value="3">拒绝申请</t-radio-button>
                  </t-radio-group>
                </t-form-item>
                <t-form-item label="处理备注" name="handleNote">
                  <t-textarea v-model="handleForm.handleNote" placeholder="请输入处理备注" />
                </t-form-item>
              </t-form>
            </div>
          </template>
        </div>
      </div>
    </t-dialog>

    <!-- 图片预览 -->
    <t-image-viewer v-model:visible="previewVisible" :images="[currentPreviewUrl]" />
  </div>
</template>

<script setup lang="ts">
import { FormInstanceFunctions, Link, MessagePlugin, Space, Tag } from 'tdesign-vue-next';
import { computed, ref } from 'vue';

import { handleAfterSales, page } from '@/api/after_sales';
import baseTable from '@/components/base-table/index.vue';
import { formatTime } from '@/utils/format';

const submitForm = ref<any>({});
const modalOpen = ref(false);
const table = ref<any>(null);

// 图片预览相关
const previewVisible = ref(false);
const currentPreviewUrl = ref('');

// 处理表单
const handleForm = ref({
  status: 1,
  handleNote: '',
});

// 表单校验规则
const rules = {
  status: [{ required: true, message: '请选择处理结果' }],
  handleNote: [{ required: true, message: '请输入处理备注' }],
};

// 搜索参数
const searchParams = computed(() => [
  {
    key: 'status',
    label: '处理状态',
    valueType: 'select',
    options: [
      { label: '待处理', value: 0 },
      { label: '处理中', value: 1 },
      { label: '已完成', value: 2 },
      { label: '已拒绝', value: 3 },
    ],
  },
  {
    key: 'type',
    label: '售后类型',
    valueType: 'select',
    options: [
      { label: '退款', value: 0 },
      { label: '退货退款', value: 1 },
      { label: '换货', value: 2 },
    ],
  },
]);

// 获取类型文本
const getTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    0: '退款',
    1: '退货退款',
    2: '换货',
  };
  return typeMap[type] || '未知';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待处理',
    1: '处理中',
    2: '已完成',
    3: '已拒绝',
  };
  return statusMap[status] || '未知';
};

// 获取状态主题
const getStatusTheme = (status: number): 'default' | 'success' | 'primary' | 'warning' | 'danger' => {
  const themeMap: Record<number, 'default' | 'success' | 'primary' | 'warning' | 'danger'> = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'danger',
  };
  return themeMap[status] || 'default';
};

// 表格列定义
const columns = computed(() => [
  {
    title: '订单编号',
    colKey: 'orderId',
    width: 180,
  },
  {
    title: '售后类型',
    colKey: 'type',
    width: 120,
    cell: (h: any, { row }: any) => getTypeText(row.type),
  },
  {
    title: '申请原因',
    colKey: 'reason',
    width: 200,
  },
  {
    title: '处理状态',
    colKey: 'status',
    width: 120,
    cell: (h: any, { row }: any) => h(Tag, { theme: getStatusTheme(row.status) }, () => getStatusText(row.status)),
  },
  {
    title: '创建时间',
    colKey: 'createTime',
    width: 180,
    cell: (h: any, { row }: any) => formatTime(row.createTime),
  },
]);

// 表格列定义（带操作列）
const columnsAction = computed(() => [
  ...columns.value,
  {
    title: '操作',
    colKey: 'op',
    width: 200,
    cell: (h: any, { row }: any) => {
      const buttons = [
        h(
          Link,
          {
            theme: 'primary',
            onClick: () => {
              submitForm.value = { ...row, images: JSON.parse(row.images) };
              handleForm.value = {
                status: 1,
                handleNote: '',
              };
              modalOpen.value = true;
            },
          },
          () => '查看详情',
        ),
      ];

      return h(Space, {}, () => buttons);
    },
  },
]);

// 处理图片预览
const handlePreviewImage = (url: string) => {
  currentPreviewUrl.value = url;
  previewVisible.value = true;
};

// 处理售后
const handleSubmit = async () => {
  try {
    await handleAfterSales(submitForm.value.id, handleForm.value.status, handleForm.value.handleNote);
    MessagePlugin.success('处理成功！');
    modalOpen.value = false;
    table.value.onSearch();
  } catch (error) {
    console.error(error);
  }
};

// 刷新
const refresh = () => {
  table.value.onSearch();
};

// 提交表单
const onModalSubmit = () => {
  if (submitForm.value.status === 0) {
    handleSubmit();
  } else {
    modalOpen.value = false;
  }
};
</script>

<style lang="less" scoped>
.feedback-detail {
  padding: 16px;

  .detail-content {
    .detail-item {
      display: flex;
      margin-bottom: 16px;

      .label {
        width: 100px;
        color: #666;
        flex-shrink: 0;
      }

      .value {
        color: #333;
        flex: 1;

        &.image-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;

          .feedback-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;

            &:hover {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }

  .handle-form {
    margin-top: 24px;
  }
}
</style>
